﻿using TripleGame.Core;
using System;

namespace TripleGame.NaiveEngine
{
    public class TripleGameNaiveEngine : ITripleGameEngine
    {
        private const char EMPTY_CELL = ' ';

        public string EngineName
        {
            get { return "Naive engine"; }
        }

        public void PerformMove(char[,] board, char playerLetter, 
            out int startX, out int startY, out int endX, out int endY)
        {
            for (startY = 0; startY < board.GetLength(0); startY++)
            {
                for (startX = 0; startX < board.GetLength(1); startX++)
                {
                    bool rightMoveValid = IsMoveValid(board, playerLetter, startY, startX, 1, 0);
                    if (rightMoveValid)
                    {
                        endX = startX + 2;
                        endY = startY;
                        return;
                    }

                    bool downMoveValid = IsMoveValid(board, playerLetter, startY, startX, 0, 1);
                    if (downMoveValid)
                    {
                        endX = startX;
                        endY = startY + 2;
                        return;
                    }

                    bool downRightMoveValid = IsMoveValid(board, playerLetter, startY, startX, 1, 1);
                    if (downRightMoveValid)
                    {
                        endX = startX + 2;
                        endY = startY + 2;
                        return;
                    }
                }
            }

            throw new InvalidOperationException("No valid moves were found.");
        }

        private bool IsMoveValid(char[,] board, char playerLetter, 
            int startRow, int startCol, int stepX, int stepY)
        {
            int row = startRow;
            int col = startCol;
            int numberOfEmptyCellsFilled = 0;
            for (int i = 1; i <= 3; i++)
            {
                if (row < 0 || row >= board.GetLength(0) ||
                    col < 0 || col >= board.GetLength(1))
                {
                    return false;
                }

                char currentCellUpcase = Char.ToUpperInvariant(board[row, col]);
                char playerLetterUpcase = Char.ToUpperInvariant(playerLetter);
                if (currentCellUpcase == EMPTY_CELL)
                {
                    numberOfEmptyCellsFilled++;
                }
                else if (currentCellUpcase != playerLetterUpcase)
                {
                    return false;
                }
                row += stepY;
                col += stepX;
            }

            if (numberOfEmptyCellsFilled == 0)
            {
                return false;
            }

            return true;
        }

    }
}
